package com.example.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.common.Result;
import com.example.entity.ApplicationDetail;
import com.example.entity.Applications;
import com.example.entity.Lawyer;
import com.example.service.ApplicationDetailService;
import com.example.service.ApplicationsService;
import com.example.entity.User;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.service.LawyerService;
import org.springframework.web.bind.annotation.*;
import com.example.exception.CustomException;
import cn.hutool.core.util.StrUtil;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.math.BigDecimal;

@RestController
@RequestMapping("/api/applications")
public class ApplicationsController {
    @Resource
    private ApplicationsService applicationsService;
    @Resource
    private ApplicationDetailService applicationDetailService;
    @Resource
    private LawyerService lawyerService;
    @Resource
    private HttpServletRequest request;


    public User getUser() {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            throw new CustomException("-1", "请登录");
        }
        return user;
    }

    @PostMapping
    public Result<?> save(@RequestBody Applications applications) {
        String applicationId = UUID.randomUUID().toString();
        // 补充填写申请人信息
        applications.setId(applicationId);
        applications.setUserName(getUser().getUsername());
        applications.setUserId(getUser().getId().intValue());
        applications.setApplicationDate(new Date());
        applications.setCreateTime(new Date());
        applications.setStatus("待审核");
        applicationsService.save(applications);
        // 保存申请记录
        ApplicationDetail applicationDetail = new ApplicationDetail();
        applicationDetail.setApplicationTitle(applications.getCaseTitle());
        applicationDetail.setApplicationId(applicationId);
        applicationDetail.setStatus("待审核");
        applicationDetail.setCreateTime(new Date());
        applicationDetailService.save(applicationDetail);
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody Applications applications) {
        //保存审批记录
        ApplicationDetail applicationDetail = new ApplicationDetail();
        applicationDetail.setApplicationId(applications.getId());
        applicationDetail.setStatus(applications.getStatus());
        applicationDetail.setUserName(getUser().getUsername());
        applicationDetail.setUserId(getUser().getId());
        applicationDetail.setAdvice(applications.getAdvice());
        applicationDetail.setCreateTime(new Date());
        applicationDetailService.save(applicationDetail);
        //查询律师信息
        Lawyer lawyer = lawyerService.getById(applications.getAssignedLawyerId());
        applications.setLawyerName(lawyer.getName());
        applications.setUpdateTime(new Date());
        return Result.success(applicationsService.updateById(applications));
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        applicationsService.removeById(id);
        QueryWrapper<ApplicationDetail> query = Wrappers.query();
        query.eq("application_id",id);
        applicationDetailService.remove(query);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> findById(@PathVariable Long id) {
        return Result.success(applicationsService.getById(id));
    }

    /**
     * 查询当前用户的申请表信息
     * @return
     */
    @GetMapping("/currentUser")
    public Result<?> findApplicationByUser() {
        LambdaQueryWrapper<Applications> query = Wrappers.<Applications>lambdaQuery().orderByDesc(Applications::getCreateTime);
        query.eq(Applications::getUserId,getUser().getId());
        List<Applications> list = applicationsService.list(query);
        for (Applications applications : list) {
            LambdaQueryWrapper<ApplicationDetail> detailQuery = Wrappers.<ApplicationDetail>lambdaQuery().orderByAsc(ApplicationDetail::getId);
            detailQuery.eq(ApplicationDetail::getApplicationId,applications.getId());
            List<ApplicationDetail> applicationDetailList = applicationDetailService.list(detailQuery);
            applications.setApplicationDetailList(applicationDetailList);
        }
        return Result.success(list);
    }

    @GetMapping
    public Result<?> findAll() {
        return Result.success(applicationsService.list());
    }

    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(required = false, defaultValue = "") String name,
                                                @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<Applications> query = Wrappers.<Applications>lambdaQuery().orderByDesc(Applications::getCreateTime);
        if (StrUtil.isNotBlank(name)) {
            query.like(Applications::getCaseTitle, name);
        }
        return Result.success(applicationsService.page(new Page<>(pageNum, pageSize), query));
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {

        List<Map<String, Object>> list = CollUtil.newArrayList();

        List<Applications> all = applicationsService.list();
        for (Applications obj : all) {
            Map<String, Object> row = new LinkedHashMap<>();
            row.put("id", obj.getId());
            row.put("用户id", obj.getUserId());
            row.put("案件标题", obj.getCaseTitle());
            row.put("案件描述", obj.getCaseDescription());
            row.put("案件类型", obj.getCaseType());
            row.put("案件地点", obj.getCaseLocation());
            row.put("相关证据材料描述或附件链接", obj.getSupportingDocuments());
            row.put("申请日期", obj.getApplicationDate());
            row.put("审核状态", obj.getStatus());
            row.put("外键关联律师表的lawyer_id", obj.getAssignedLawyerId());
            row.put("创建日期", obj.getCreateTime());
            row.put("更新时间", obj.getUpdateTime());

            list.add(row);
        }

        // 2. 写excel
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("申请表管理信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(System.out);
    }

    @GetMapping("/upload/{fileId}")
    public Result<?> upload(@PathVariable String fileId) {
        String basePath = System.getProperty("user.dir") + "/src/main/resources/static/file/";
        List<String> fileNames = FileUtil.listFileNames(basePath);
        String file = fileNames.stream().filter(name -> name.contains(fileId)).findAny().orElse("");
        List<List<Object>> lists = ExcelUtil.getReader(basePath + file).read(1);
        List<Applications> saveList = new ArrayList<>();
        for (List<Object> row : lists) {
            Applications obj = new Applications();
            obj.setUserId(Integer.valueOf((String) row.get(1)));
            obj.setCaseTitle((String) row.get(2));
            obj.setCaseDescription((String) row.get(3));
            obj.setCaseType((String) row.get(4));
            obj.setCaseLocation((String) row.get(5));
            obj.setSupportingDocuments((String) row.get(6));
            obj.setApplicationDate(DateUtil.parseDateTime((String) row.get(7)));
            obj.setStatus((String) row.get(8));
            obj.setAssignedLawyerId(Integer.valueOf((String) row.get(9)));
            obj.setCreateTime(DateUtil.parseDateTime((String) row.get(10)));
            obj.setUpdateTime(DateUtil.parseDateTime((String) row.get(11)));

            saveList.add(obj);
        }
        applicationsService.saveBatch(saveList);
        return Result.success();
    }

}
